package name.file.wwplusfastfood;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;

import com.bappi.utils.Constants;

public class TabsController extends TabActivity {
	
	private static final String KEY_FAVORITE_RESTAURANTS = "KEY_FAVORITE_RESTAURANTS";
	public static final String KEY_FAVORITES_UPDATE_TIME = "KEY_FAVORITES_UPDATE_TIME";
	public static final String KEY_TAB_0_CLICKED = "KEY_TAB_0_CLICKED";
	public static final String KEY_TAB_1_CLICKED = "KEY_TAB_1_CLICKED";

	private static final String[] TABS = { "Tab1", "Tab2", "Tab3" };

	private static final String[] TAB_TITLES = { "Restaurants", "My Favorites",
			"Extras" };

	private TabHost tabs = null;

	public void changeTab(int index) {
		tabs.setCurrentTab(index);
	}

	private static SharedPreferences preferences;
	private static List<ListItem> listItems;
	private static List<ListItem> favoriteItems;
	private static SparseArray<ListItem> array;

	public static final SharedPreferences getSharedPreferences() {
		return preferences;
	}
	
	public static final List<ListItem> getAllRestaurents() {
		return listItems.subList(0, listItems.size());
	}

	public static final List<ListItem> getFavoriteRestaurents() {
		return favoriteItems.subList(0, favoriteItems.size());
	}

	public static final ListItem getRestaurent(int key) {
		return array.get(key);
	}

	public static final void addToFavorite(ListItem listItem) {
		try {
			listItem.setFavorite(true);
			if (!favoriteItems.contains(listItem)) {
//				favoriteItems.add(listItem);
				favoriteItems.add(0, listItem);
				JSONArray ja = new JSONArray();
				for(int i=0;i<favoriteItems.size();i++){
					ja.put(favoriteItems.get(i).getId());
				}
				preferences.edit().putString(KEY_FAVORITE_RESTAURANTS, ja.toString()).commit();
				preferences.edit().putLong(KEY_FAVORITES_UPDATE_TIME, System.currentTimeMillis()).commit();
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	public static final void removeFromFavorite(ListItem listItem) {
		listItem.setFavorite(false);
		favoriteItems.remove(listItem);
		JSONArray ja = new JSONArray();
		for(int i=0;i<favoriteItems.size();i++){
			ja.put(favoriteItems.get(i).getId());
		}
		preferences.edit().putString(KEY_FAVORITE_RESTAURANTS, ja.toString()).commit();
		preferences.edit().putLong(KEY_FAVORITES_UPDATE_TIME, System.currentTimeMillis()).commit();
	}

	@Override
	public void onCreate(Bundle icicle) {
		try {
			super.onCreate(icicle);
			setContentView(R.layout.tabs_controller);
			preferences = PreferenceManager
					.getDefaultSharedPreferences(this);
			JSONArray ja = new JSONArray(new String(getAssetsFileData(this,
					"json/data.json")));
			JSONObject jo;
			ListItem listItem;
			listItems = new ArrayList<ListItem>();
			favoriteItems = new ArrayList<ListItem>();
			array = new SparseArray<ListItem>();
			for (int i = 0; i < ja.length(); i++) {
				jo = ja.getJSONObject(i);
				jo.put("id", i);
				listItem = new ListItem();
				listItem.setDrawableName(jo.getString("img"));
				listItem.setHtmlName(jo.getString("html"));
				listItem.setTitle(jo.getString("title"));
				listItem.setId(jo.getInt("id"));
				listItem.setFavorite(false);
				JSONArray tags = jo.getJSONArray("tags");
				List<String> tgs = new ArrayList<String>();
				for(int j=0;j<tags.length();j++){
					tgs.add(tags.getString(j));
				}
				listItem.setTags(tgs);
				
				listItems.add(listItem);
				array.put(listItem.getId(), listItem);
//				//
//				JSONArray tags = new JSONArray();
//				tags.put(jo.getString("title").toLowerCase());
//				jo.put("tags", tags);
//				//
				
			}
//			//
//			 File ROOT = Environment.getExternalStorageDirectory();
//						 FileOutputStream fos = new FileOutputStream(new File(ROOT,
//						 "data.txt"));
//						 fos.write(ja.toString().getBytes());
//						 fos.close();
//						 //
			
			String favorites  = preferences.getString(KEY_FAVORITE_RESTAURANTS, null); 
			if(favorites!=null){
				ja = new JSONArray(favorites);
				for (int i = 0; i < ja.length(); i++) {
					int id = ja.getInt(i);
					listItem = array.get(id);
					listItem.setFavorite(true);
					favoriteItems.add(listItem);
				}
			}
			
			setDefaultTab(0);
			tabs = getTabHost();
			for (int i = 0; i < TABS.length; i++) {
				TabHost.TabSpec tab = tabs.newTabSpec(TABS[i]);

				ComponentName oneActivity = new ComponentName(getApplication()
						.getPackageName(), getApplication().getPackageName()
						+ "." + TABS[i]);

				tab.setContent(new Intent().setComponent(oneActivity));
				int id = R.drawable.custom_tab_1;
				switch (i) {
				case 0:
					id = R.drawable.custom_tab_1;
					break;
				case 1:
					id = R.drawable.custom_tab_2;
					break;
				case 2:
					id = R.drawable.custom_tab_3;
					break;
				}
				tab.setIndicator(new MyTabIndicator(this, id, TAB_TITLES[i]));
				tabs.addTab(tab);
			}
			
			getTabWidget().getChildAt(0).setOnClickListener(
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							if (getTabHost().getCurrentTab() != 0) {
								getTabHost().setCurrentTab(0);

							}
							preferences
									.edit()
									.putLong(KEY_TAB_0_CLICKED,
											System.currentTimeMillis())
									.commit();
						}
					});
			getTabWidget().getChildAt(1).setOnClickListener(
					new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							if (getTabHost().getCurrentTab() != 1) {
								getTabHost().setCurrentTab(1);

							}
							preferences
									.edit()
									.putLong(KEY_TAB_1_CLICKED,
											System.currentTimeMillis())
									.commit();
						}
					});

			int startCount = preferences.getInt(Constants.KEY_APP_START_COUNTER, 0)+1;
			preferences.edit().putInt(Constants.KEY_APP_START_COUNTER, startCount).commit();
			if(!preferences.getBoolean(Constants.KEY_APP_RATED, false)){
				for(int i=0;i<Constants.RATING_POPUP_INDEXES.length;i++){
					if(Constants.RATING_POPUP_INDEXES[i] == startCount){
						showRatingPopup();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static class MyTabIndicator extends LinearLayout {
		public MyTabIndicator(Context context, int iconId, String label) {
			super(context);
			View tab = LayoutInflater.from(context).inflate(
					R.layout.tab_indicator, this);
			ImageView iv = (ImageView) tab.findViewById(R.id.tab_image);
			iv.setImageResource(iconId);
			TextView tv = (TextView) tab.findViewById(R.id.tab_label);
			tv.setText(label);
		}
	}

	public static byte[] getAssetsFileData(Context context, String fileName)
			throws Exception {
		byte[] ret = null;
		try {
			InputStream is = context.getAssets().open(fileName);
			byte[] data = new byte[2048];
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int read;
			while ((read = is.read(data)) != -1) {
				baos.write(data, 0, read);
			}
			is.close();
			ret = baos.toByteArray();
			baos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
	
	
	private void showRatingPopup() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setMessage(getString(R.string.rate_us))
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								openMarket();
							}
						})
				.setNegativeButton(getString(R.string.later),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {

							}
						});
		final AlertDialog alert = builder.create();
		alert.show();
	}
	
	private void openMarket() {
		try {
			preferences.edit().putBoolean(Constants.KEY_APP_RATED, true).commit();
			String packageName = getApplication().getPackageName();
			Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("market://details?id=" + packageName));
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}